import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { EquipmentServiceProxy, EquipmentEditDto, ComboboxItemDto } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { InputSwitchModule } from 'primeng/primeng';

import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'createOrEditEquipmentModal',
    templateUrl: './create-or-edit-equipment-modal.component.html'
})

export class CreateOrEditEquipmentModalComponent extends AppComponentBase {

    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('dateStartPicker') dateStartPicker: ElementRef;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;

    equipment: EquipmentEditDto = new EquipmentEditDto();
    teamGroups: ComboboxItemDto[];


    constructor(
        injector: Injector,
        private _equipmentService: EquipmentServiceProxy
    ) {
        super(injector);
    }

    show(id?: number): void {
        this.active = true;

        this._equipmentService.getEquipmentForEdit(id).subscribe(result => {
            this.equipment = result.equipment;

            this.equipment.teamGroupId = this.equipment.teamGroupId ? this.equipment.teamGroupId : 1;
            this.teamGroups = result.teamGroups;

            this.modal.show();
        });
    }

    save(): void {
        this.saving = true;

        this._equipmentService.createOrUpdateEquipment(this.equipment)
            .pipe(finalize(() => this.saving = false))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}
